const express = require("express")
const router = express.Router()

const jwt = require('jsonwebtoken')
const { BadRequest, Unauthorized, NotFound } = require("http-errors")
const bcrypt = require('bcryptjs')
const { Op } = require("sequelize")

const { User } = require("../models")
const { success } = require("../utils/response")

/**
 * 用户注册
 */
router.post("/sign_up", async (req, res, next) => {
  try {
    const body = {
      name: req.body.name,
      email: req.body.email,
      password: req.body.password,
      role: 0
    }

    const user = await User.create(body)
    delete user.dataValues.password

    success(res, "用户注册成功", { user }, 201)

  } catch (error) {
    console.log(error)
    next(error)
  }
})

router.post("/sign_in", async (req, res, next) => {
  try {
    const { login, password } = req.body

    if (!login) {
      throw new BadRequest("邮箱/用户名必须填写")
    }
    if (!password) {
      throw new BadRequest("密码必须填写")
    }

    const condition = {
      where: {
        [Op.or]: [
          { email: login },
          { name: login }
        ]
      }
    }

    const user = await User.findOne(condition)

    if (!user) {
      throw new NotFound("用户有不存在，无法登录")
    }

    const isPasswordValid = bcrypt.compareSync(password, user.password)
    if (!isPasswordValid) {
      throw new Unauthorized('密码错误。');
    }

    const token = jwt.sign({
      userId: user.id
    }, process.env.SECRET, { expiresIn: '30d' })

    success(res, "登录成功", { token })

  } catch (error) {
    next(error)
  }
})

module.exports = router